package Offer;


import java.util.Arrays;
import java.util.Random;

/*
    输入整数数组 arr ，找出其中最小的 k 个数。
    例如，输入 4、5、1、6、2、7、3、8 这8个数字，则最小的4个数字是1、2、3、4。

    这题实际考的就是排序算法；这个题如果是在机试中遇到，那就是要手写排序了，绝对不会给你调用api的
* */
public class T40_getLeastNumbers {

    private Random random = new Random(System.currentTimeMillis());


    public int[] getLeastNumbers(int[] arr, int k) {

//        单路快排
//        quickSort(arr, 0, arr.length - 1);

        return Arrays.copyOf(arr, k);
    }

    /**
     * 快速排序
     */
    public void quickSort(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }
        int partition = partition_of_two(nums, left, right);
        quickSort(nums, left, partition - 1);
        quickSort(nums, partition + 1, right);
    }

    /**
     * 单路快排
     * @return 返回pivot的正确索引
     */
    public int partition(int[] nums, int left, int right) {
        int randomIndex = left + this.random.nextInt(right - left + 1);
        swap(nums, left, randomIndex);
        int pivot = nums[left];

        int j = left;
        for (int i = left + 1; i <= right; i++) {
            if (nums[i] <= pivot) {
                j++;
                swap(nums, i, j);
            }
        }
        swap(nums, left, j);
        return j;
    }

    /**
     * 双路快排
     */
    public int partition_of_two(int[] nums, int left, int right) {
        int randomIndex = left + this.random.nextInt(right - left + 1);
        swap(nums, left, randomIndex);
        int pivot = nums[left];

        int le = left + 1;
        int ge = right;

        while (true) {
            while (le <= ge && nums[le] < pivot) {
                le++;
            }
            while (le <= ge && nums[ge] > pivot) {
                ge--;
            }
            if (le > ge) {
                break;
            }
            swap(nums, le, ge);
            le++;
            ge--;
        }
        swap(nums, left, ge);
        return ge;
    }

    /**
     * 三路快排
     */
    public void quickSort_of_three(int[] nums, int left, int right) {
        int randomIndex = left + random.nextInt(right - left + 1);
        swap(nums, left, randomIndex);
        int pivot = nums[left];

        int lt = left + 1;
        int gt = right;
        int i = left + 1;

//        [left,lt) < pivot
//        [lt,i) == pivot
//        (gt,right] > pivot
        while (i <= gt) {
            if (nums[i] < pivot) {
                swap(nums, lt, i);
                lt++;
                i++;
            } else if (nums[i] == pivot) {
                i++;
            } else {
                swap(nums, i, gt);
                gt--;
            }
        }

        swap(nums, left, lt - 1);
        quickSort_of_three(nums, left, lt - 2);
        quickSort_of_three(nums, gt + 1, right);
    }

    /**
     * 交换数组两个元素
     */
    void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

}